from fastapi import APIRouter, Depends, HTTPException, status
from schemas.agent import AgentResponse, AgentBase
from services.agent_service import AgentService
from schemas.base import create_response
import asyncio
import traceback

router = APIRouter(prefix="/agent", tags=["agent"])
service = AgentService()

@router.post("")
async def create_or_update_agent(agent_data: AgentBase):
    try:
        result = await service.upsert_agent(agent_data)
        # 根据createdAt和updatedAt判断操作类型
        if result.createdAt == result.updatedAt:
            message = "AI分身新增成功"
        else:
            message = "AI分身更新成功"
            
        response = await create_response(200, message, result)
        return response
    except asyncio.TimeoutError:
        raise HTTPException(
            status_code=504,
            detail={
                "code": 504,
                "message": f"AI分身处理超时",
                
            } )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": 500,
                "message": f"AI分身处理失败: {str(e)}",
                
            }
        )
 
    
    

@router.get("/{userId}")
async def get_agent(userId: str):
    try:
        agent = await service.get_agent(userId)
        if not agent:
            response={"code": 404, "message": f"未查询到AI分身: {userId}"}
        else:    
            response = await create_response(200, "AI分身查询成功", agent)
        return response
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": 500,
                "message": f"AI分身查询失败: {str(e)}",
                
            }
        )

@router.delete("/{userId}")
async def delete_agent(userId: str):
    try:
        success = await service.delete_agent(userId)
 
        if success:
            response = await create_response(200, "AI分身删除成功")
        else:
            response={"code": 404, "message": f"未查询到AI分身: {userId}"}
        return response
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail={
                "code": 500,
                "message": f"AI分身删除失败: {str(e)}",

            }

        )
    

